package org.space.galaxyCabinet.handler.impl;

import com.alibaba.fastjson2.JSONObject;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.WriteApi;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import lombok.extern.slf4j.Slf4j;
import org.space.galaxyCabinet.annotation.GuiguEmqx;
import org.space.galaxyCabinet.constant.EmqxConstants;
import org.space.galaxyCabinet.domain.DeviceLog;
import org.space.galaxyCabinet.handler.MassageHandler;
import org.space.galaxyCabinet.service.InfluxDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Date;

@Slf4j
@Component
@GuiguEmqx(topic = EmqxConstants.DEVICE_ALL_LOG)
public class DeviceLogHandler implements MassageHandler {

    @Autowired
    private InfluxDBService influxDBService;

//    @Autowired
//    private InfluxDBClient influxDBClient;

    @Override
    public void handleMessage(JSONObject message) {
        log.info(getClass().getName()+" => 开始处理设备属性上报消息...");
        try {
            // 检查消息是否为空
            if (message == null || message.isEmpty()) {
                log.warn("收到空消息");
                return;
            }
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setDeviceNo(message.getString("deviceNo"));
            deviceLog.setType(message.getString("type"));
            deviceLog.setContent(message.getString("content"));
            deviceLog.setTimestamp(Instant.now());

            log.info("上传到influxDB:{}", influxDBService.uploadedDeviceLog(deviceLog));
//            try (WriteApi writeApi = influxDBClient.getWriteApi()) {
//                writeApi.writeMeasurement(WritePrecision.NS, deviceLog);
//                writeApi.flush(); // 强制立即写入
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
